<template>
  <div v-clickoutside="handleClose" class="el-select">
    <el-input size="small" :readonly="true" :on-icon-click="iconClick" v-model="showValue" @focus="handleShow" :icon="showValue===null?'caret-top':'circle-cross'"></el-input>
    <transition
      name="el-zoom-in-top">
      <div v-show="visible">
        <el-scrollbar
          tag="div"
          wrap-class="el-select-dropdown__wrap">
          <ymy-project-tree @loaded="setShowValue" :search="search" @node-click="selectValue" :expand-on-click-node="false"></ymy-project-tree>
        </el-scrollbar>
      </div>
    </transition>
  </div>
</template>


<script>

  import ymyProjectTree from './ymyProjectTree';
  import clickoutside from 'element-ui/src/utils/clickoutside';

  export default {
    data() {
      return {
        visible: false,
        currValue:this.value,
        showValue:null
      };
    },
    props:{
      search:{type:Boolean,default:false},
      value:{type:[String,Number,Array]},
      beforeSelect:{type:Function},
      afterSelect:{type:Function}
    },
    directives: {clickoutside},
    components: {
      ymyProjectTree,
    },
    methods: {
      setShowValue(list){
        const _this = this;
        list.forEach(item=>{
          if(item.id === _this.value){
            _this.showValue = item.label;
          }
        });
      },
      handleClose() {
        this.visible = false;
      },
      handleShow() {
        this.visible = true;
      },
      selectValue(data,node,component){
        if(this.beforeSelect){
          if(!this.beforeSelect(data)){
            return;
          }
        }
        this.currValue = data.id;
        this.showValue = data.label;
        if(this.afterSelect){
          this.afterSelect(data);
        }
      },
      iconClick(){
        if(this.showValue===null){
          this.handleShow();
        }else{
          this.clear();
        }
      },
      clear(){
        this.currValue = null;
        this.showValue = null;
      }
    },
    watch:{
      currValue(){
        this.$emit('input',this.currValue);
      },
      value(){
        if(this.currValue!==this.value){
          this.currValue = this.value;
        }
      }
    }
  };

</script>
